﻿using System;
using System.Windows;
using System.Windows.Controls;

namespace Red.Controls
{
    /// <summary>
    ///
    /// </summary>
    public class FilteredTreeView : TreeView
    {
        private Func< object, bool > _filter;

        public Func< object, bool > Filter
        {
            get { return _filter; }

            set {
                _filter = value;
                if ( _filter != null ) {
                    DoFiltering( this );
                }
            }
        }

        private void DoFiltering( ItemsControl container )
        {
            foreach ( object item in container.Items ) {
                bool passes = _filter( item );

                TreeViewItem treeItem = container.ItemContainerGenerator.ContainerFromItem( item ) as TreeViewItem;
                if ( treeItem != null ) {
                    if ( passes ) {
                        treeItem.Visibility = Visibility.Visible;
                    }
                    else {
                        treeItem.Visibility = Visibility.Collapsed;
                    }
                    treeItem.IsExpanded = true;
                    DoFiltering( treeItem ); // go down recursively
                }
            }
        }

        static FilteredTreeView()
        {
           // DefaultStyleKeyProperty.OverrideMetadata( typeof( FilteredTreeView ), new FrameworkPropertyMetadata( typeof( FilteredTreeView ) ) );
        }
    }
}
